/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: AlipayApiController.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2015年3月14日
 */
package cn.apestar.common.pay.zfb.web;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.apestar.common.pay.zfb.entity.NotifyModel;
import cn.apestar.common.pay.zfb.service.AlipayService;
import cn.apestar.common.pay.zfb.util.AlipayNotify;
import cn.apestar.common.service.ServiceException;

/**
 * 
 * @author: weihuang.peng
 * @version Revision: 0.0.1
 * @Date: 2015年3月14日
 */
@Controller
@RequestMapping("/api/modules/alipay")
public class AlipayApiController  {

	@Autowired
	private AlipayService alipayService;
	
	private static Logger log  = LoggerFactory.getLogger(AlipayApiController.class);
	
	/**
	 * 支付宝回调
	 * @author: xiaoming.wang(改成自己的名字)
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("/notify")
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response, @ModelAttribute NotifyModel model) throws Exception {
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//验证成功
		if(AlipayNotify.verify(params)){
			//支付成功
			if (model.getTrade_status().equals("TRADE_SUCCESS")) {
				log.debug("支付成功：" + model);
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//如果有做过处理，不执行商户的业务程序
//				alipayService.updateCartInfo(model);
			}
			//验证成功
			writeText(response, "success");
			System.out.println(model.getTrade_status());
		} else {
			//验证失败
			writeText(response, "fail");
		}
	}
	
	/**
	 * 文本字符的输出
	 * @author: weihuang.peng
	 * @param response
	 * @param data
	 */
	public void writeText(HttpServletResponse response, String data) {
		PrintWriter localPrintWriter = null;
		try {
			localPrintWriter = response.getWriter();
			localPrintWriter.print(data);
			localPrintWriter.flush();
		} catch (Exception e) {
			throw new ServiceException();
		} finally {
			if (localPrintWriter != null && !localPrintWriter.checkError()) {
				localPrintWriter.close();
			}
		}
	}
}
